<template>
  <div class=''>
    <!-- 上传附件 -->
    <a-upload v-if="props.fileType === 'attachment'" v-model:file-list="fileList" :before-upload="beforeUpload"
      @change="handleChange" @remove="handleRemove">
      <slot name="content">
        <a-button type="link">
          <PaperClipOutlined />{{ $t('添加附件') }}
        </a-button>
      </slot>
    </a-upload>
    <a-upload v-else class="show" v-model:file-list="fileList" name="file" :before-upload="beforeUpload"
      @change="handleChange">
      <slot name="content">
        <a-input-group compact>
          <a-input v-if="!state.showUploadBtn" :bordered="false" v-model:value="updateName" 
            style="width: calc(100% - 150px);border: none !important;border-bottom: 1px solid #b8b5b5 !important;border-radius: 0%"
            disabled />
          <div v-if="state.showUploadBtn">
            <img :src="fileData.imageUrl ? fileData.imageUrl : formState[anyValue.key].filePath"
              style="width: 20px;height: 20px;" />
            <span>&nbsp;&nbsp;&nbsp;{{ fileData.name ? fileData.name :
              state.formState[state.anyValue.key].originalFileName
              }}</span>
            <span>&nbsp;&nbsp;&nbsp;{{
              parseInt(fileData.size) > 0 ? (fileData.size / 1024).toFixed(2) :
                ((state.formState[state.anyValue.key].fileSize) /
                  1024).toFixed(2) }}Kb</span>
          </div>
          <!-- <a-button class="btn">{{ $t('浏览') }}</a-button> -->
          &nbsp;&nbsp;&nbsp;
          <!-- style="display: flex;flex-direction: row" -->
          <a-button size="small">
            <upload-outlined></upload-outlined>
            {{ $t('changePic') }}
          </a-button>

        </a-input-group>
      </slot>
    </a-upload>
  </div>
</template>
<script setup lang="ts">
const { t: $t } = useI18n();
import { Postupload } from '@/api/public';
import { itforceUploadDatas } from '@/hooks/dyformHook/dyformHook';
import { PaperClipOutlined } from '@ant-design/icons-vue';
const updateName = ref('Choose file...')
const fileList: any = ref([])
const fileValue: any = ref(null)
const emits = defineEmits(['uploadParams', 'beforeUpload', 'remove', 'handleChange'])
const props = defineProps({
  fileName: {
    required: true,
    type: String,
    default: () => '',
  },
  isShow: {
    required: true,
    type: Boolean,
    default: () => false,
  },
  fileType: {
    required: true,
    type: String,
    default: () => 'default',
  },
  currentIndex: { type: Number, default: 0 },//当前第几行
  anyValue: { type: [Object, Array, String, Number], default: () => { return {} || [] } },//传入任意数据
  showUploadBtn: [Boolean],//展示改变图片
  formState: [Object]//传进来表单数据
})
watch(() => props.fileName,
  (newVal) => {
    updateName.value = newVal
  },
  {
    flush: 'post',
  }
);

const fileData: any = ref({
  imageUrl: null,
  name: null,
  size: 0
})
const state: any = reactive({
  formState: props.formState,
  showUploadBtn: props.showUploadBtn,
  anyValue: props.anyValue
})
const fileParams: any = ref(null)
const list = ref([])
const handleChange = async (info: any) => {
  await getBase64(info.file, (base64Url: string) => {
    fileData.value = {
      imageUrl: base64Url,
      name: info.file.name,
      size: info.file.size
    }
  })
};

const beforeUpload = async (file: any) => {

  fileValue.value = file
  fileList.value = [...(fileList.value || []), file];
  if (props.fileType === 'attachment') {
    handleUpload()
  } else {
    updateName.value = file.name
  }
  emits('beforeUpload', file, props.currentIndex, props.anyValue)
  return false;
};


const handleUpload = async () => {
  let formData = ref(new FormData());
  formData.value.append('file', fileValue.value);
  if (fileValue.value) {
    const { data } = await Postupload(formData.value)
    fileParams.value = data
    if (props.fileType === 'attachment') {
      list.value.push(data)
    }
    emits('uploadParams', fileParams.value, props.currentIndex, props.anyValue)
  }

  // emits('uploadParams', data, props.currentIndex, props.anyValue)
};

const handleRemove = (row) => {
  const removeParams = list.value.filter(item => item.originalFileName !== row.originFileObj.name)
  emits('remove', removeParams)
}

//处理图片转base64
async function getBase64(img: Blob, callback: (base64Url) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

defineExpose({
  handleUpload,
  handleRemove,
  handleChange
});
</script>
<style scoped lang='scss'>
.btn {
  background-color: #eaecef;
  font-weight: bolder;
}

.show {
  :deep(.ant-upload-list-item) {
    display: none;
  }
}

::v-deep {
  .ant-upload {
    width: 100%;
  }

  // 全局样式修改回来
  .ant-input {
    color: #242424;
    border: 1px solid #dadada !important;
    // border-radius: 4px !important;
  }

  // .ant-upload-wrapper .ant-upload-list .ant-upload-list-item {
  //   display: none;
  // }
}
</style>
